// store/modules/models.js

const state = () => ({
    models: [],
    selectedModelId: ''
});

const mutations = {
    SET_SELECTED_MODEL(state, modelId) {
        state.selectedModelId = modelId;
    },
    SET_DEFAULT_MODEL_FOR_TYPE(state, productType) {
        const defaultModel = state.models.find(
            model => model.productType === productType && model.isDefault
        );
        if (defaultModel) {
            state.selectedModelId = defaultModel.id;
        }
    },
    SET_MODELS(state, payload) {
        state.models = payload
    }
};

const actions = {
    setSelectedModel({ commit }, modelId) {
        commit('SET_SELECTED_MODEL', modelId);
    },
    setDefaultModelForType({ commit }, productType) {
        commit('SET_DEFAULT_MODEL_FOR_TYPE', productType);
    },
    selectModel({ commit, dispatch, rootState }, modelId) {
        const selectedModel = rootState.models.models.find(m => m.id === modelId);

        console.log('Model selection:', {
            modelId,
            selectedModel,
            defaultDesignId: selectedModel?.defaultDesignId,
            availableDesigns: rootState.designs.designs
        });

        if (selectedModel) {
            commit('SET_SELECTED_MODEL', modelId);

            const defaultDesign = rootState.designs.designs.find(d =>
                d.id === selectedModel.defaultDesignId
            );

            console.log('66', rootState.designs.designs)
            console.log('77', selectedModel)
            console.log('Default design found:', defaultDesign);

            if (defaultDesign) {
                dispatch('designs/setSelectedDesign', defaultDesign.id, { root: true });
            }
        }
    },
    setModels({ commit }, models) {
        commit('SET_MODELS', models)
    }
};

const getters = {
    models: state => state.models,
    selectedModel: state => state.models.find(m => m.id === state.selectedModelId),
    selectedModelId: state => state.selectedModelId,
    modelsByProductType: state => productType =>
        state.models.filter(m => m.productType === productType),
    defaultModelByProductType: state => productType =>
        state.models.find(m => m.productType === productType && m.isDefault)
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
};
